<?php
/**
 * Created by PhpStorm.
 * User: alex
 * Date: 2018/8/19
 * Time: 下午5:36
 */

namespace sms\aliyun;

use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
use Aliyun\Core\Config;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Core\Profile\DefaultProfile;
use sms\AbstractSms;
use Symfony\Component\DependencyInjection\ContainerInterface;


// 加载区域结点配置
Config::load();
class AliyunSMS extends AbstractSms
{
    protected static $accessKeyId;
    protected static  $accessKeySecret;
    protected static  $signName;
    protected  $typeTemplateCodes;
    static $acsClient = null;

    public function __construct(ContainerInterface $container = null)
    {
        parent::__construct($container);

        self::$accessKeyId = $this->getParameter('SMS_aliyun_accessKeyId');
        self::$accessKeySecret = $this->getParameter('SMS_aliyun_accessKeySecret');
        self::$signName = $this->getParameter('SMS_aliyun_signName');
        $this->typeTemplateCodes = $this->getParameter('SMS_aliyun_typeTemplateCodes');
    }

    /**
     * 取得AcsClient
     *
     * @return DefaultAcsClient
     */
    public static function getAcsClient() {
        //产品名称:云通信流量服务API产品,开发者无需替换
        $product = "Dysmsapi";

        //产品域名,开发者无需替换
        $domain = "dysmsapi.aliyuncs.com";

        //AccessKeyId
        $accessKeyId = self::$accessKeyId; // AccessKeyId

        $accessKeySecret = self::$accessKeySecret; // AccessKeySecret

        // 暂时不支持多Region
        $region = "cn-hangzhou";

        // 服务结点
        $endPointName = "cn-hangzhou";


        if(static::$acsClient == null) {

            //初始化acsClient,暂不支持region化
            $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);

            // 增加服务结点
            DefaultProfile::addEndpoint($endPointName, $region, $product, $domain);

            // 初始化AcsClient用于发起请求
            static::$acsClient = new DefaultAcsClient($profile);
        }
        return static::$acsClient;
    }

    /**
     * 发送短信
     *
     * @param $phone
     * @param $content
     * @param string $templateCode
     * @return array|mixed
     */
    public function sendSms($phone, $content, $templateCode = ''){

        if(empty($content)){
            $content['code']  = '';
        }

        // 初始化SendSmsRequest实例用于设置发送短信的参数
        $request = new SendSmsRequest();

        // 必填，设置短信接收号码
        $request->setPhoneNumbers($phone);

        // 必填，设置签名名称，应严格按"签名名称"填写
        $request->setSignName(self::$signName);

        // 必填，设置模板CODE，应严格按"模板CODE"填写
        $request->setTemplateCode($templateCode);

        // 可选，设置模板参数, 假如模板中存在变量需要替换则为必填项
        $request->setTemplateParam(json_encode(  // 短信模板中字段的值
            $content , JSON_UNESCAPED_UNICODE));

        // 发起访问请求
        $acsResponse = static::getAcsClient()->getAcsResponse($request);

        return $this->returnRewrite($acsResponse);
    }


    /**
     * 重写返回值
     *
     * @param $r
     * @return array
     */
    public function returnRewrite($r)
    {
        $result = array();
        if ($r->Code == 'OK') {
            $result['errorCode'] = 0;
            $result['message'] = '发送成功';
        }else{
            switch ($r->Code){
                case 'isp.RAM_PERMISSION_DENY':
                    $r = 'RAM权限DENY';
                    break;

                case 'isv.OUT_OF_SERVICE':
                    $r = '短信业务停机';
                    break;

                case 'isv.PRODUCT_UN_SUBSCRIPT':
                    $r = '未开通云通信产品的阿里云客户';
                    break;

                case 'isv.PRODUCT_UNSUBSCRIBE':
                    $r = '产品未开通';
                    break;

                case 'isv.ACCOUNT_NOT_EXISTS':
                    $r = '账户不存在';
                    break;

                case 'isv.ACCOUNT_ABNORMAL':
                    $r = '账户异常';
                    break;

                case 'isv.SMS_TEMPLATE_ILLEGAL':
                    $r = '短信模板不合法';
                    break;

                case 'isv.SMS_SIGNATURE_ILLEGAL':
                    $r = '短信签名不合法';
                    break;

                case 'isv.INVALID_PARAMETERS':
                    $r = '参数异常';
                    break;

                case 'isp.SYSTEM_ERROR':
                    $r = '系统错误';
                    break;

                case 'isv.MOBILE_NUMBER_ILLEGAL':
                    $r = '非法手机号';
                    break;

                case 'isv.MOBILE_COUNT_OVER_LIMIT':
                    $r = '手机号码数量超过限制';
                    break;

                case 'isv.TEMPLATE_MISSING_PARAMETERS':
                    $r = '模板缺少变量';
                    break;

                case 'isv.BUSINESS_LIMIT_CONTROL':
                    $r = '请勿重复操作';
                    break;

                case 'isv.INVALID_JSON_PARAM':
                    $r = 'JSON参数不合法，只接受字符串值';
                    break;

                case 'isv.BLACK_KEY_CONTROL_LIMIT':
                    $r = '黑名单管控';
                    break;

                case 'isv.PARAM_LENGTH_LIMIT':
                    $r = '参数超出长度限制';
                    break;

                case 'isv.PARAM_NOT_SUPPORT_URL':
                    $r = '不支持URL';
                    break;

                case 'isv.AMOUNT_NOT_ENOUGH':
                    $r = '短信业务余额不足';
                    break;

                case 'isv.TEMPLATE_PARAMS_ILLEGAL':
                    $r = '模板变量里包含非法关键字';
                    break;

                default:
                    $r = "短信次数超过限制";
                    break;
            }

            $result['errorCode'] = 1;
            $result['message'] = $r;
        }

        return $result;
    }

    /**
     * 重写模板
     * @param $phone
     * @param $sale
     * @param $type
     * @return string
     */
    public function template($phone, $sale, $type)
    {
        $content = $sale;
        return $content;
    }


    /**
     * 发送短信验证码
     *
     * @param $phone
     * @param $sale
     * @param $type
     * @return array|mixed
     */
    public function userMessage($phone, $sale, $type)
    {
        $typeTemplateCodes = $this->typeTemplateCodes;
        $flag = false;
        $templateCode = '';
        $result['errorCode'] = 1;

        foreach ($typeTemplateCodes as $k=>$v){
            if(!array_key_exists('type',$v)){
                $result['message'] = '阿里云配置错误';
            }

            if(!array_key_exists('templateCode',$v)){
                $result['message'] = '阿里云配置错误';
            }

            if($v['type'] == $type){
                $flag = true;
                $templateCode = $v['templateCode'];
                break;
            }
        }

        if($flag == false){
            $result['message'] = '类型溢出';
            return $result;
        }


        $content = $this->template($phone, $sale, $type);
        return $this->sendSms($phone, ['code' => $content],$templateCode);
    }

}